package day05;

import beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.Row;

/**
 * Flink Table API 与 SQL —— 自定义标量函数
 *
 * 阿里云文档：https://help.aliyun.com/document_detail/69472.html
 *
 * @author lvbingbing
 * @date 2022-01-21 16:53
 */
public class FlinkTableApi09 {
    public static void main(String[] args) throws Exception {
        // 1、获取可执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        int parallelism = 1;
        env.setParallelism(parallelism);
        // 2、创建表环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 3、从文件中读取数据
        DataStream<SensorReading> dataStreamSource = env.readTextFile("input/sensor.txt")
                .map(e -> {
                    String[] split = e.split(",");
                    return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
                });
        // 4、将流数据转换成表
        Table dataTable = tableEnv.fromDataStream(dataStreamSource, "id, timestamp as ts, temperature as temp");
        // 5、自定义标量函数
        userDefinedScalarFunction(dataTable, tableEnv);
        // 6、触发程序执行
        env.execute();
    }

    /**
     * 自定义标量函数，实现求 id 的 hash 值
     *
     * @param dataTable 数据表
     * @param tableEnv  表执行环境
     */
    private static void userDefinedScalarFunction(Table dataTable, StreamTableEnvironment tableEnv) {
        // 1、创建自定义标量函数对象
        HashCodeScalarFunction hashCodeScalarFunction = new HashCodeScalarFunction(5);
        // 2、在环境中注册标量函数
        tableEnv.registerFunction("hashCodeScalar", hashCodeScalarFunction);
        // 3、使用自定义标量函数
        // 3.1、tableApi
        Table resTable = dataTable.select("id, ts, hashCodeScalar(id)").where("id === 'sensor_1'");
        DataStream<Row> rowDataStream = tableEnv.toAppendStream(resTable, Row.class);
        rowDataStream.print("resTable");
        // 3.2、sql
        tableEnv.createTemporaryView("sensor", dataTable);
        String sql = "select id, ts, hashCodeScalar(id) from sensor where id = 'sensor_1'";
        Table sqlQuery = tableEnv.sqlQuery(sql);
        DataStream<Row> rowDataStream1 = tableEnv.toAppendStream(sqlQuery, Row.class);
        rowDataStream1.print("sqlQueryTable");
    }

    /**
     * 自定义标量函数，实现求 id 的 hash 值
     */
    public static class HashCodeScalarFunction extends ScalarFunction {

        private static final long serialVersionUID = -2991835284189017558L;

        private int factor = 13;

        public HashCodeScalarFunction(int factor) {
            this.factor = factor;
        }

        public HashCodeScalarFunction() {
        }

        public int eval(String str) {
            return str.hashCode() * factor;
        }
    }
}
